package com.sptpc.book.service;

import com.sptpc.book.controller.request.NewBookRequest;
import com.sptpc.book.model.Book;
import com.sptpc.book.model.Category;
import com.sptpc.book.model.Order;
import com.sptpc.book.repository.BookRepository;
import com.sptpc.book.repository.CategoryRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class BookService {
    @Autowired
    private CategoryRepository categoryRepository;
    @Autowired
    private BookRepository bookRepository;

    public Book saveBook(Book book){
        return bookRepository.save(book);
    }

    public List<Book> findAll() {
        return bookRepository.findAll(Sort.by(Sort.Direction.ASC, "id"));
    }

    public List<Book> getAllBooks(Long categoryId) {
        return bookRepository.getBooksByCategory_Id(categoryId);
    }

    public Book findOne(String name) {
        Optional<Book> book = bookRepository.findBookByNameLike(name);
        if (book.isPresent()) {
            return book.get();
        } else {
            return null;
        }
    }

    public Book getBook(String name) {
        Optional<Book> book = bookRepository.findBookByNameLike(name);
        if (book.isPresent()) {
            return book.get();
        } else {
            return null;
        }
    }

    public Book getBook(Long id) {
        return bookRepository.getOne(id);
    }

    public Book saveBook(NewBookRequest bookRequest) {
        Optional<Category> category =categoryRepository.findById(bookRequest.getCategoryId());
        if (category.isPresent()){
             Book book =new Book();
             BeanUtils.copyProperties(bookRequest,book);
             book.setCategory(category.get());
            return bookRepository.save(book);
        }
        return null;
    }
}
